package com.xiege.springboot.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiege.springboot.common.Result;
import com.xiege.springboot.utils.TokenUtils;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;

import com.xiege.springboot.service.ICollectionService;
import com.xiege.springboot.entity.Collection;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 榭歌
 * @since 2023-04-02
 */
@RestController
@RequestMapping("/collection")
public class CollectionController {

    @Resource
    private ICollectionService collectionService;

    // 新增或者更新
    @PostMapping
    public Result save(@RequestBody Collection collection) {
        //新增收藏
        if(collection.getId() == null){
            collection.setUserId(TokenUtils.getCurrentUser().getId());
            collection.setTime(DateUtil.now());
        }
        collectionService.saveOrUpdate(collection);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        collectionService.removeById(id);
        return Result.success();
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        collectionService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(collectionService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(collectionService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                                @RequestParam Integer pageSize) {
        QueryWrapper<Collection> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        return Result.success(collectionService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }

}

